<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/23
 * Time: 15:19
 */

namespace app\logic\index\user;


use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\GuzzleNew;
use app\common\lib\Spreadsheet;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\logic\service\alarm\QiCatAlarmLogic;
use app\model\novel\NovelSpreadModel;
use app\model\user\UserPlatformAccountModel;
use support\Cache;
use support\Log;

class UserSpreadLogic extends BaseLogic
{
    protected $model;

    protected static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->model = \app\model\user\UserSpreadKeywordModel::getInstance();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function getList($param)
    {
        try{
            $this->getQiCatKeywordList();
        }catch (\Throwable $e){}

        $where = [
            'isdel'=>0,
            'novel_sn'=>$param['novel_sn'],
            'user_sn'=>request()->curUserId,
        ];

        if(!empty($param['status'])){
            $status = [];
            if($param['status']==1){
                $status = [0,1];
            }elseif ($param['status']==2){
                $status = [2,4];
            }elseif ($param['status']==3){
                $status = [3,5,6];
            }
            $status && $where[] = ['status','in',$status];
        }
        $fields = ['id','user_sn','novel_sn','keyword','reject_reason','created_at','status','work_link_data'];
        $order = ['created_at', 'desc'];

        $list =  $this->model->index($where, $fields, $order);
        $statusMap = [
            '0'=>'审核中',
            '1'=>'审核中',
            '2'=>'审核通过',
            '3'=>'审核失败',
            '4'=>'审核通过',
            '5'=>'审核失败',
            '6'=>'审核失败',
        ];
        $statusValMap = [
            '0'=>'1',
            '1'=>'1',
            '2'=>'2',
            '4'=>'2',
            '3'=>'3',
            '5'=>'3',
            '6'=>'3',
        ];
        foreach ($list['data'] as $val){
            $val['status_text'] = $statusMap[$val['status']]??'';
            $val['status'] = (int) ($statusValMap[$val['status']]??'1');

            $workLinkData = $val['work_link_data'] ? json_decode($val['work_link_data'],true) : [];
            $val['is_submit_link'] = $workLinkData ? '1' : '0';
            $val['created_at'] = date('Y.m.d',strtotime($val['created_at']));
            unset($val['work_link_data']);
        }
        return $list;
    }

    protected function getQiCatKeywordList()
    {
        //5分钟之后才能请求一次列表
        $cache = Cache::get('getQiCatKeywordList');
        if($cache){
            return false;
        }
        $param = [
            'product_id'=>1,
            'page'=>1,
            'page_size'=>100,
            'start_date'=>date('Y-m-d',strtotime('-7 day')),
            'end_date'=>date('Y-m-d'),
        ];
        // 准备请求头
        $headers = [
            'X-Qm-Devops-Token'=>config('param.qi_cat_token')
        ];
        $path = 'api/v1/promotion/keyword_page?'.http_build_query($param);
        $result = (new GuzzleNew())->get('https://kol.wtzw.com/',$path,$headers);
        if(!empty($result['code']) && $result['code']==200 && !empty($result['data']['list'])){
            foreach($result['data']['list'] as $val){
                $where = [
                    'user_sn'=>$val['kol_name'],
                    'book_id'=>$val['book_id'],
                    'keyword'=>$val['search_keyword'],
                     ['status','in',[0,1,2,4]],
                ];
                $this->model->getWhere($where)->update(['status'=>$val['status_text_code'],'reject_reason'=>$val['reject_reason']]);
            }
        }
        Cache::set('getQiCatKeywordList',date('Y-m-d H:i:s'),300);
        return true;
    }

    public function submitKeyword($param)
    {
        if(Common::setnx('submitKeyword_spread_'.request()->curUserId)==false){
            throw new IndexException(4020,'请不要频繁提交');
        }
        if(request()->curUserInfo['mobile']==false){
            throw new IndexException(4020,'手机号登录才可提交关键词');
        }

        $novel = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$param['novel_sn']])->first();
        if($novel==false){
            throw new IndexException(4020,'小说已下架或者找不到了');
        }

        $count = $this->model->getWhere(['keyword'=>$param['keyword'],'isdel'=>0,['status','in',[0,1,2,4]]])->count();
        if($count){
            throw new IndexException(4020,'关键词已重复');
        }
        $insert = [
            'user_sn'=>request()->curUserId,
            'keyword'=>$param['keyword'],
            'novel_sn'=>$param['novel_sn'],
            'book_id'=>$novel['book_id'],
            'book_name'=>$novel['title'],
            'status'=>0,
        ];
        $id = $this->model->insertGetId($insert);

        //todo 生成导入文档，批量导入关键词
        $data = [
            [
                'Bookid',
                '达人名',
                '关键词',
            ],
            [
                $novel['book_id'],
                request()->curUserId,
                $param['keyword'],
            ]
        ];
        $fileName = runtime_path('qicat_spread_keyword_'.Common::getRequestId().'.xlsx');
        Spreadsheet::getInstance()->writerExcelFile($data,$fileName);
        if(is_file($fileName)){
           $result = $this->uploadKeyword($fileName);
           @unlink($fileName);
           if($result==true){
               $this->model->getWhere(['id'=>$id])->update(['status'=>1]);
           }
        }

        return $id;
    }

    protected function uploadKeyword($fileName)
    {
        try{
            $client = new \GuzzleHttp\Client([
                'base_uri' => 'https://kol.wtzw.com/',
                'timeout'  => 30,
                // https请求
                'verify' => strpos('https://kol.wtzw.com/', 'https:') == false ? true : false,
            ]);
            // 准备multipart数据
            $multipartData = [
                [
                    'name'     => 'file',
                    'contents' => fopen($fileName, 'r')
                ]
            ];
            // 准备请求头
            $headers = [
                'X-Qm-Devops-Token'=>config('param.qi_cat_token')
            ];
            // 创建请求
            $request = new \GuzzleHttp\Psr7\Request('POST', 'api/v1/promotion/upload_file', $headers, new \GuzzleHttp\Psr7\MultipartStream($multipartData));
            // 发送请求
            $response = $client->send($request);
            // 输出响应体
            $data = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);

            if(!empty($data['data']['address'])){
                $param = [
                    'product_id'=>1,
                    'upload_url'=>$data['data']['address'],
                ];
                $result = (new GuzzleNew())->post('https://kol.wtzw.com/','api/v1/promotion/add_keywords',$param,$headers,'json');
                if(!empty($result['code']) && $result['code']==200){
                    return true;
                }
            } else {
                QiCatAlarmLogic::getInstance()->errorAlarm($data, __FILE__, __LINE__);
            }
            return false;
        }catch (\Exception $e){
            return false;
        }catch (\Throwable $e){
            return false;
        }
        return false;
    }

    public function submitWorkLink($param)
    {
        $keyword = $this->model->find($param['keyword_id']);
        if($keyword==false){
            throw new IndexException(4020,'关键词不存在');
        }
        if(in_array($keyword['status'],[2,4])==false){
            throw new IndexException(4020,'审核通过才能填写作品链接');
        }

        $preg = '/http[s]?:\/\/[\w|\/|\.|\-|=|\?|:|%|&]+/';
        preg_match_all($preg,$param['work_link_content'],$data);
        if(empty($data[0][0])){
            throw new IndexException(4020,'作品链接格式错误');
        }
        $workLink = $data[0][0];
        $workLinkDatas = $keyword['work_link_data'] ? json_decode($keyword['work_link_data'],true) : [];
//        $workLinks = array_column($workLinkDatas,'work_link');
//        if(in_array($workLink,$workLinks)){
//            throw new IndexException(4020,'作品链接已填写,无需重复填写');
//        }

        //todo 生成导入文档，批量回填链接
        $data = [
            [
                '关键词',
                '链接',
            ],
            [
                $keyword['keyword'],
                $workLink,
            ]
        ];
        $fileName = runtime_path('qicat_spread_keyword_link_'.Common::getRequestId().'.xlsx');
        Spreadsheet::getInstance()->writerExcelFile($data,$fileName);
        if(is_file($fileName)){
            $result = $this->uploadKeywordLink($fileName);
            @unlink($fileName);
            if($result==true){
                $workLinkData = [
                    'work_link'=>$workLink,
                    'work_link_content'=>$param['work_link_content'],
                    'platform_account_id'=>$param['platform_account_id'],
                    'upload_time'=>date('Y-m-d H:i:s'),
                ];
                array_push($workLinkDatas,$workLinkData);

                $keyword->work_link_data = json_encode($workLinkDatas,256);
                return $keyword->save();
            }
        }

        throw new IndexException(4020,'作品链接填写失败,请稍后再试');
    }

    protected function uploadKeywordLink($fileName)
    {
        try{
            $client = new \GuzzleHttp\Client([
                'base_uri' => 'https://kol.wtzw.com/',
                'timeout'  => 30,
                // https请求
                'verify' => strpos('https://kol.wtzw.com/', 'https:') == false ? true : false,
            ]);
            // 准备multipart数据
            $multipartData = [
                [
                    'name'     => 'file',
                    'contents' => fopen($fileName, 'r')
                ]
            ];
            // 准备请求头
            $headers = [
                'X-Qm-Devops-Token'=>config('param.qi_cat_token')
            ];
            // 创建请求
            $request = new \GuzzleHttp\Psr7\Request('POST', 'api/v1/promotion/upload_file', $headers, new \GuzzleHttp\Psr7\MultipartStream($multipartData));
            // 发送请求
            $response = $client->send($request);
            $content = $response->getBody()->getContents();
            // 输出响应体
            $data = \GuzzleHttp\json_decode($content, true);

            if(!empty($data['data']['address'])){
                $param = [
                    'product_id'=>1,
                    'upload_url'=>$data['data']['address'],
                ];
                $result = (new GuzzleNew())->post('https://kol.wtzw.com/','api/v1/promotion/add_keyword_links',$param,$headers,'json');

                if(!empty($result['code']) && $result['code']==200){
                    return true;
                }
            } else {
                QiCatAlarmLogic::getInstance()->errorAlarm($data, __FILE__, __LINE__);
            }
            return false;
        }catch (\Exception $e){
            return false;
        }catch (\Throwable $e){
            return false;
        }
        return false;
    }

    public function deleteKeyword($param)
    {
        $keyword = $this->model->find($param['keyword_id']);
        if($keyword==false){
            throw new IndexException(4020,'关键词不存在');
        }
        $keyword->isdel = time();
        return $keyword->save();

    }


    /**
     * 获取关键词历史链接列表
     * @param $param
     * @return array
     */
    public function getUserHistoryKeyWordLink($param): array
    {
        $keyword = $this->model->find($param['keyword_id']);

        $data = !empty($keyword) && !empty($keyword->work_link_data) ? json_decode($keyword->work_link_data, 1) : [];

        $account = UserPlatformAccountModel::getInstance()->getWhere(['user_sn'=>request()->curUserId, 'isdel'=>0])->get();
        if (!empty($data) && !empty($account)) {
            $account = array_column($account->toArray(), null, 'id');
            foreach ($data as &$datum) {
                $id = $datum['platform_account_id'] ?? 0;
                if (!$id) continue;
                $datum['platform_name'] = !empty($account[$id]) ? $account[$id]['platform_name'] : '';
                $datum['logo'] = !empty($account[$id]) ? $account[$id]['logo'] : '';
            }
        }

        return $data;
    }
    /**
     * 获取关键词历史链接列表
     * @param $param
     * @return bool
     */
    public function delUserHistoryKeyWordLink($param): bool
    {
        $keyword = $this->model->find($param['keyword_id']);
        $workLinkIds = !empty($param['work_link_ids']) && is_array($param['work_link_ids']) ? $param['work_link_ids'] : [];

        $data = !empty($keyword) && !empty($keyword->work_link_data) ? json_decode($keyword->work_link_data, 1) : [];

        if (!empty($data)) {
            foreach ($workLinkIds as $index) {
                unset($data[$index]);
            }
            $work_link_data = json_encode(array_values($data));
            $res = $this->model->getWhere(['id'=>$param['keyword_id'], 'user_sn'=>request()->curUserId])->update(['work_link_data'=>$work_link_data]);
            return (bool)$res;
        }

        return true;
    }
}